package auth

import (
	"context"
	"github.com/go-kit/kit/endpoint"
	"gysa-share01/common"
	"gysa-share01/exception"
	user2 "gysa-share01/models/user"
)

var (
	usernameCannotBeEmptyException = exception.NewGeneralException("用户名不得为空", exception.PARAMETER_ERROR)
	passwordCannotBeEmptyException = exception.NewGeneralException("密码不得为空", exception.PARAMETER_ERROR)
	nicknameCannotBeEmptyException = exception.NewGeneralException("昵称不得为空", exception.PARAMETER_ERROR)
)

func MakeRegisterByPwdEndpoint(svc AuthServiceInterface) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req := request.(registerByPwdRequest)
		if req.UserName == "" {
			err = usernameCannotBeEmptyException
			return
		}
		if req.Password == "" {
			err = passwordCannotBeEmptyException
			return
		}
		if req.Nickname == "" {
			err = nicknameCannotBeEmptyException
			return
		}
		user := user2.User{
			Username: req.UserName,
			Password: req.Password,
			Money:    0,
			Nickname: req.Nickname,
		}

		token, err := svc.RegisterByPwd(&user)
		if err != nil {
			return
		}

		response = registerByPwdResponse{
			Response: common.Response{},
			Token:    token,
		}

		return

	}
}

func MakeLoginEndpoint(svc AuthServiceInterface) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req := request.(loginRequest)
		if req.UserName == "" {
			err = usernameCannotBeEmptyException
			return
		}
		if req.Password == "" {
			err = passwordCannotBeEmptyException
			return
		}

		token, err := svc.LoginByPwd(req.UserName, req.Password)
		if err != nil {
			return
		}

		response = registerByPwdResponse{
			Response: common.Response{},
			Token:    token,
		}

		return

	}
}
